﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;
using QDT.Common;
using QDT.Core.Assignments;
using QDT.Core.Deals;
using QDT.Core.Domain;
using QDT.Core.Experience;
using QDT.Core.Members;
using QDT.Core.Orders;
using QDT.Core.Projects;
using QDT.MVC.Security;
using QDT.Services.Assignments;
using QDT.Services.Credits;
using QDT.Services.Deals;
using QDT.Services.Members;
using QDT.Services.Orders;
using QDT.Services.Projects;
using QDT.Web.Code;
using QDT.Web.Code.Attributes;
using QDT.Web.Code.Enums;
using QDT.Web.Models;

namespace QDT.Web.Controllers
{
    [DefaultAuthorize]
    public abstract class UserBaseController : BaseController
    {
        protected new User User { get { return QDTContext.Current.User; } }
    }

    [HttpsRequire]
    public partial class UserController : UserBaseController
    {
        private const int ProjectFlag = 870;
        private readonly IUserService _userService;
        private readonly IQureyService _qureyService;

        //payment支付服务
        private static ICreditService CreditService { get { return IoC.Resolve<ICreditService>(); } }
        private static IAssignmentService AssignmentService { get { return IoC.Resolve<IAssignmentService>(); } }

        //订单服务
        private static IOrderService OrderService { get { return IoC.Resolve<IOrderService>(); } }

        public UserController(IUserService userService, IQureyService qureyService)
        {
            Check.Argument.IsNotNull(userService, "userService");

            _userService = userService;
            _qureyService = qureyService;
        }

        [OutputCache(Duration = 60)]
        public ActionResult UserMenu(MenuRoute route)
        {
            return PartialView("_UserMenu", route);
        }

        public ActionResult Index()
        {
            User.UserSta = _userService.UserSta(User.UserName);
            return View(User);
        }

        [OutputCache(Duration = 60)]
        public ActionResult InvestList(int id)
        {
            var model = new UserInvestModel();
            var credits = DbProvider.D<Credit>().Where(x => x.UserID == User.ID && x.Money > 0);

            model.RepayCount = credits.Count(x => x.InnerStatus == 3);
            model.RepidCount = credits.Count(x => x.InnerStatus == 4);
            model.IngCount = credits.Count(x => x.InnerStatus <= 2);

            if (model.RepayCount > 0) model.RepayAmount = credits.Where(x => x.InnerStatus == 3).Sum(x => x.Money);
            if (model.RepidCount > 0) model.RepidAmount = credits.Where(x => x.InnerStatus == 4).Sum(x => x.Money);
            if (model.IngCount > 0) model.IngAmount = credits.Where(x => x.InnerStatus <= 2).Sum(x => x.Money);

            return PartialView(model);
        }

        public ActionResult AllInvestList(int? page)
        {
            const int pageSize = 6;
            var pageNumber = page ?? 1;
            var result = _qureyService.GetCreditList(User.ID, pageNumber - 1, pageSize, ProjectStatus.Repaying);

            return View(result);
        }

        public ActionResult ShowBackPlan(int id)
        {
            var credit = DbProvider.GetByID<Credit>(id);
            var project = DbProvider.GetByID<Project>(credit.ProjectID);
         
            if (project != null)
            {
                
                ViewBag.projectid = credit.ProjectID;
                ViewBag.Credit = credit;
                ViewBag.Project = project;

                var strategy = new RepayStrategyFactory().GetRepayStrategy(project);
                var list = strategy.GetCreditRepaymenScheme(credit);

                return View(list);
            }
            return View();
        }

        [OutputCache(Duration = 60)]
        public ActionResult LogList(int id)
        {
            var source = DbProvider.D<UserTransLog>().Where(x => x.UserID == User.ID && x.InnerTrade != 4 && x.InnerTrade != 5)
                                  .OrderByDescending(x => x.ID);
            return PartialView(source.ToPagedList(0, 4));
        }

        public ActionResult AllLogList(int? page, DateTime? starTime, DateTime? endTime, int? tradetype)
        {
            const int pageSize = 7;
            var pageNumber = page ?? 1;
            if (tradetype != -1 && tradetype!=null)
            {
                if (string.IsNullOrEmpty(starTime.ToString()) || string.IsNullOrEmpty(endTime.ToString()))
                {
                    var source = DbProvider.D<UserTransLog>().Where(x => x.UserID == User.ID && x.InnerTrade != 4 && x.InnerTrade != 5 && x.InnerTrade == tradetype)
                                      .OrderByDescending(x => x.ID);
                    ViewBag.tradetype = tradetype;
                    return View(source.ToPagedList(pageNumber - 1, pageSize));
                }
                else
                {
                    var startime = starTime.Value.ToString("yyyy-MM-dd");
                    var endtime = endTime.Value.ToString("yyyy-MM-dd");
                    ViewBag.startime = startime;
                    ViewBag.endtime = endtime;
                    var source = DbProvider.D<UserTransLog>().Where(x => x.UserID == User.ID && x.InnerTrade != 4 && x.InnerTrade != 5 && x.InnerTrade == tradetype && x.Time >= starTime && x.Time <= endTime).OrderByDescending(x => x.ID);
                    ViewBag.tradetype = tradetype;
                    return View(source.ToPagedList(pageNumber - 1, pageSize));
                }
               
            }
            else
            {
                if (string.IsNullOrEmpty(starTime.ToString()) || string.IsNullOrEmpty(endTime.ToString()))
                {
                    var source = DbProvider.D<UserTransLog>().Where(x => x.UserID == User.ID && x.InnerTrade != 4 && x.InnerTrade != 5)
                                      .OrderByDescending(x => x.ID);
                    return View(source.ToPagedList(pageNumber - 1, pageSize));
                }
                else
                {
                    var startime = starTime.Value.ToString("yyyy-MM-dd");
                    var endtime = endTime.Value.ToString("yyyy-MM-dd");
                    ViewBag.startime = startime;
                    ViewBag.endtime = endtime;
                    var source = DbProvider.D<UserTransLog>().Where(x => x.UserID == User.ID && x.InnerTrade != 4 && x.InnerTrade != 5 && x.Time >= starTime && x.Time <= endTime).OrderByDescending(x => x.ID);
                    return View(source.ToPagedList(pageNumber - 1, pageSize));
                }
            }
        }

        public ActionResult RechargeDetail(int? page)
        {
            const int pageSize = 8;
            var pageNumber = page ?? 1;

            var chargelist = DbProvider.D<ChargeOrder>().Where(x => x.UserID == User.ID).OrderByDescending(x => x.ID).ToPagedList(pageNumber-1, pageSize);
            return View(chargelist);
        }

        public ActionResult ExtractionDetail(int? page)
        {
            const int pageSize = 8;
            var pageNumber = page ?? 1;
            var extrlist = DbProvider.D<UserCarry>().Where(x => x.UserId == User.ID).OrderByDescending(x => x.ID).ToPagedList(pageNumber-1, pageSize);

            return View(extrlist);
        }

        public ActionResult InvestOver(int? page)
        {
            const int pageSize = 6;
            var pageNumber = page ?? 1;
            var result = _qureyService.GetCreditList(User.ID, pageNumber - 1, pageSize, ProjectStatus.Repaid);

            return View(result);
        }

        public ActionResult Investing(int? page)
        {
            const int pageSize = 6;
            var pageNumber = page ?? 1;
            var result = _qureyService.GetCreditList(User.ID, pageNumber - 1, pageSize, ProjectStatus.Progress);
            return View(result);
        }

        public ActionResult RepayInvest(int? page)
        {
            const int pageSize = 10;
            var pageNumber = page ?? 1;
            var result = _qureyService.GetCreditList(User.ID, pageNumber-1, pageSize, ProjectStatus.Repaying);

            return View("AllInvestList", result);
        }

        public ActionResult CompletedInvest(int? page)
        {
            const int pageSize = 10;
            var pageNumber = page ?? 1;

            var result = _qureyService.GetCreditList(User.ID, pageNumber - 1, pageSize, ProjectStatus.Repaid);

            ViewBag.Route = InvestRoute.CompletedInvest;

            return View("AllInvestList", result);
        }

        public ActionResult CreditList(int? page)
        {
            const int pageSize = 5;
            var pageNumber = page ?? 1;
            var credits = CreditService.GetCanAssigmentCredit(User.ID, pageNumber, pageSize);
            return View(credits);
        }

        public ActionResult AssignmentList(int? page)
        {
            var assignments = AssignmentService.GetAssignmentPaged(page, User.ID, (int)AssignmentStatus.Progress);
            ViewBag.Status = AssignmentStatus.Progress;
            return View(assignments);
        }

        public ActionResult AssignCompleteList(int? page)
        {
            var assignments = AssignmentService.GetAssignmentPaged(page, User.ID, (int)AssignmentStatus.Completed);
            ViewBag.Status = AssignmentStatus.Completed;
            return View("AssignmentList", assignments);
        }

        public ActionResult _UserBanner()
        {
            User.UserSta = _userService.UserSta(User.UserName);
            return PartialView(User);
        }

        public ActionResult FriendInteract()
        {
            return View();
        }

        public ActionResult Experience(int? page)
        {
            const int pageSize = 5;
            var pageNumber = page ?? 1;

            var credits = DbProvider.D<ExpCredit>().Where(x => x.UserId == User.ID).OrderByDescending(x=>x.ID);
            return View(credits.ToPagedList(pageNumber-1, pageSize));
        }

        public ActionResult UrgentContact(int userid)
        {
            User user = _userService.GetUserByID(userid);
            return View(user);
        }

        [HttpPost]
        public ActionResult UrgentContact(UrgentContact model)
        {
            if (!ModelState.IsValid) return Error();
            if (User.ID != model.Id) return Error("信息错误");

            User user = _userService.GetUserByID(model.Id);
            if (string.IsNullOrEmpty(model.UrgentMobile)||string.IsNullOrEmpty(model.UrgentPerson))
            {
                return Error("信息填写不完整");
            }
            user.ChangeUrgentContact(model.UrgentPerson,model.UrgentMobile);
            _userService.UpdateUser(user);
            return Success("账户修改成功");
        }
    }
}
